package dataBase;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

public class CodeTable extends SqlTable {

	public CodeTable(String tableName, List<ColumnValue> schema, String engine) {
		super(tableName, schema, engine);
	}

	public int getLastVersion(Statement stmt, String cid) {
		if ((stmt == null) || (cid == null)) {
			return -1;
		}
		String query = "SELECT MAX(version) as version FROM " + tableName
				+ " WHERE cid = '" + cid + "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			if (rs.next()) {
				return Integer.parseInt((String) rs.getObject("version"));
			}
			return -1;
		} catch (Exception e) {
			return -1;
		}

	}

	public ResultSet searchByCid(Statement stmt, String cid) {
		String query = "SELECT * FROM " + tableName + " WHERE cid= '" + cid
				+ "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			return rs;
		} catch (Exception e) {
			return null;
		}
	}

	public String searchByCidVersion(Statement stmt, String cid, String version) {
		String query = "SELECT body FROM " + tableName + " WHERE cid= '" + cid
				+ "' " + "AND version='" + version + "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			if (rs.next()) {
				return rs.getString("body");
			} else {
				return "no match found";
			}
		} catch (Exception e) {
			return null;
		}
	}

	public boolean isOwner(Statement stmt, String cid, String version,
			String uid) {
		String query = "SELECT * FROM " + tableName + " WHERE cid= '" + cid
				+ "' " + "AND version='" + version + "' AND uid='" + uid + "';";
		try {
			ResultSet rs = stmt.executeQuery(query);
			if (rs.next()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
}
